<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}">
    <div v-loading="pageLoading" class="issue-invoice-detail-container no-margin mobile-radius">
      <template v-if="!permissionDenied">
        <ProgressStep v-if="!showMobilePage" :mode="2" :step-list="stepList" :order-status="stepActiveId" :is-show-correct="false" :is-expedited="issueInvoiceInfo.isExpedited"/>
        <explanation :explanation="explanationObj" :countdown="true" :style="`${showMobilePage ? 'margin-bottom: 0px' : ''}`" @queryProcessData="queryProcessData"/>
        <div :style="`${showMobilePage ? 'padding-top: 8px' : ''}`" class="issue-invoice-detail-content small-padding">
          <!-- 申请信息详情 -->
          <ApplicationInfo :application-info="issueInvoiceInfo" :show-mobile-page="showMobilePage" style="margin-bottom: 25px;"/>
          <TaxpayerInfo
            :taxpayer-info="issueInvoiceInfo"
            :show-mobile-page="showMobilePage"
            :is-complate="stepActiveId === PROGRESS_STEP.FINISHED || isRevoke"
            style="margin-bottom: 36px;"/>
          <!-- 订单信息详情 -->
          <!-- <RelatedOrderList
          v-if="issueInvoiceInfo.businessType === 1"
          :total-amount="issueInvoiceInfo.orderTotalAmount"
          :operate-data="processData.operation"
          :show-mobile-page="showMobilePage"
          :detail-data="issueInvoiceInfo.orderInfo"
          is-issue-invoice-module
          class="order-info-table"/> -->
          <!-- 关联流水信息 -->
          <ReceiptInfo
            ref="receiptInfoRef"
            :table-data="issueInvoiceInfo.financeTxnList || []"
            :set-events="operationSetEvents.includes(EVENT_TYPE.RELEATE_FINANCE_TXN)"
            :is-current-version="isCurrentVersion"
            :is-current-user-approval="isCurrentUserApproval"
            :issue-id="issueId"
            :application-info="issueInvoiceInfo"
            :process-status="issueInvoiceInfo.processStatus"
            :tax-payer="issueInvoiceInfo.taxpayer"
            style="margin-bottom: 30px;"
            @selectFinance="selectFinance"
            @handleDelete="handleDeleteReceipt"
          />
          <!--合同信息-->
          <InvoiceAndContract
            v-if="issueInvoiceInfo.isSign === 1"
            ref="contractInfoRef"
            :show-mobile-page="showMobilePage"
            :is-edit="false"
            :title="'合同信息'"
            :style="{marginTop: issueInvoiceInfo.businessType === 1 ? '32px' : '24px'}"
            :type="1"
            is-issue-invoice-module
            show-empty
            style="margin-bottom: 40px;"
            hide-all-operation
            title-size="16px"
            placeholder="请输入合同编号/合同名称"/>
          <InvoiceInfo
            ref="invoiceInfoRef"
            :show-mobile-page="showMobilePage"
            :is-edit="canEditInvoiceInfo" />
          <el-image v-if="isRevoke" :src="revokeImg" class="revoke-img"/>
        </div>
        <ExamineAndApprove
          ref="examineAndApproveRef"
          :disabled="pageLoading"
          :show-print="!showMobilePage"
          :process-id="processId"
          :main-id="issueId"
          :version="version"
          :get-comments-api="getIssueInvoiceComments"
          :comment-add-api="issueInvoiceCommentAdd"
          :process-revocation-api="issueInvoiceProcessRevocation"
          :process-recall-api="issueInvoiceProcessRecall"
          :process-audit-api="issueInvoiceProcessAudit"
          :create-user="createUser"
          :business-type="BUSINESS_TYPE.ISSUE_INVOICE"
          :process-type="PROCESS_TYPE.ISSUE_INVOICE"
          :audit-schedule-data="auditScheduleData"
          :senders="senders"
          :default-aduitor-list="proposerUser?[proposerUser]:[]"
          :approval-module-type="APPROVAL_MODULE_TYPE.INVOICE_ISSUE"
          :print-data="issueInvoiceInfo"
          :submit-event-edit="saveNodeEventInfo"
          :is-apply="isApply"
          :show-sign-up-slot="showSaveBtn"
          next-approve-module-id="issueId"
          redirect-url="/businessPage/issueInvoiceDetail"
          detail-page-router-name="issueInvoiceDetail"
          edit-page-router-name="issueInvoiceEdit"
          @toBack="toBack"
          @setProcessData="setProcessData"
          @handlePressSend="handlePressSend"
          @getAuditSchedule="getAuditSchedule"
          @queryProcessData="queryProcessData"
          @handleCreateNew="handleCreateNew('issueInvoiceEdit',{id: issueId},{reapplyId: processId})"
          @handleSendMsg="handleSendMsg"
          @handleSender="handleSender"
          @handleModify="handleModify('issueInvoiceEdit',{id: issueId},{remodifyId: processId})"
          @getHistoryDetail="getHistoryDetail"
          @setCurrentVersion="setCurrentVersion"
          @freshDetail="queryIssueInvoiceDetail"
          @handleCancelPress="handleCancelPress"
        >
          <div v-if="showSaveBtn" slot="signUp" >
            <el-button :style="`${showMobilePage ? 'margin: 0' : ''}`" :loading="saveLoading" type="primary" size="small" @click="saveNodeEventInfo(2)">保存</el-button>
          </div>
        </ExamineAndApprove>
      </template>
      <DeniedPlaceholder v-else />
      <ding-ding-dialog
        ref="pressSendDialogRef"
        :btn1="'确认加急'"
        :btn2="'取消'"
        :show-send-checkbox="false"
        :select-with-user-load="false"
        :default-list="pressDefaultList"
        redirect-url="/businessPage/issueInvoiceDetail"
        summary-title="加急原因"
        title="催办通知"
        @handelOK="toSend" />
    </div>
  </div>
</template>
<script>
// 组件
import ListTab from '@/components/ListTab';
import ProgressStep from '@/components/CreateOrder/orderDetail/step';
import explanation from '@/components/Common/explanation';
import ApplicationInfo from './module/applicationInfo';
import TaxpayerInfo from './module/taxpayerInfo';
import InvoiceInfo from './module/invoiceInfo';
// import RelatedOrderList from '@/views/legal/detail/module/relatedOrderList';
import ReceiptInfo from '../create/module/receiptInfo';
import InvoiceAndContract from '@/components/CreateOrder/InvoiceAndContract';
// 工具函数
import { mapState } from 'vuex';
import { PROGRESS_STEP } from '@/utils/const/energy';
import { BUSINESS_TYPE, PROCESS_TYPE, EVENT_TYPE } from '@/utils/const/process';
import { hasRouteAuth } from '@/utils/permission';
import { APPROVAL_MODULE_TYPE } from '@/utils/const';
// 图片
import revokeImg from '@/assets/auditProcess/process_status_3.png';
import emptyIcon from '@/assets/home/emptyIcon.png';
// API
import {
  storeIssueInvoiceInfo,
  getIssueInvoiceDetail,
  issueInvoiceCommentAdd,
  getIssueInvoiceComments,
  issueInvoiceProcessRevocation,
  issueInvoiceProcessRecall,
  issueInvoiceProcessAudit,
  storeIssueFinance
} from '@/api/issueInvoice';
import schedule from '@/mixins/schedule';
import ExamineAndApprove from '@/components/Common/ExamineAndApprove';
import { showModal } from '@/utils/message';

export default {
  components: {
    ListTab,
    ProgressStep,
    ApplicationInfo,
    InvoiceInfo,
    // RelatedOrderList,
    ReceiptInfo,
    InvoiceAndContract,
    explanation,
    ExamineAndApprove,
    TaxpayerInfo
  },
  mixins: [schedule],
  data() {
    return {
      EVENT_TYPE,
      APPROVAL_MODULE_TYPE,
      flag: true,
      revokeImg,
      emptyIcon,
      issueId: '', // 开票申请id
      processId: '', // 流程id
      issueInvoiceInfo: {},
      pageLoading: false,
      permissionDenied: false, // 详情页是否可查看
      BUSINESS_TYPE,
      PROGRESS_STEP,
      PROCESS_TYPE,
      issueInvoiceCommentAdd,
      getIssueInvoiceComments,
      issueInvoiceProcessRevocation,
      issueInvoiceProcessRecall,
      issueInvoiceProcessAudit,
      activeTab: '',
      stepActiveId: PROGRESS_STEP.PENDING,
      processData: {// 流程信息
        list: [],
        operation: {
          auth: [],
          content: null
        }
      },
      invoiceVersion: null, // 发票信息版本，用于多人保存时校验
      isRevoke: false,
      listLoading: false,
      operationSetEvents: [],
      saveLoading: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isCreate() { // 创建人
      return this.userInfo.id === this.issueInvoiceInfo.creatorId;
    },
    // 发票信息是否可编辑
    invoiceInfoIsEdit() {
      return this.issueInvoiceInfo.isEditInvoice && this.issueInvoiceInfo.isApprover;
    },
    stepList() {
      return [
        { name: '待提交', id: PROGRESS_STEP.PENDING },
        { name: '审批中', id: PROGRESS_STEP.UNDER_REVIEW },
        { name: '已完成', id: PROGRESS_STEP.FINISHED }
      ];
    },
    createUser() {
      let user = { id: this.issueInvoiceInfo.creatorId, userName: this.issueInvoiceInfo.creator };
      if (this.isCreate) {
        user = this.userInfo;
      }
      return user;
    },
    proposerUser() { // 申请人
      if (!this.issueInvoiceInfo || !this.issueInvoiceInfo.proposerId) {
        return null;
      }
      return { id: this.issueInvoiceInfo.proposerId, userName: this.issueInvoiceInfo.proposer };
    },
    isCurrentUserApproval() {
      if (this.auditScheduleData) {
        const currentNode = this.auditScheduleData.process && this.auditScheduleData.process.find(el => el.nodeStatus === 1) || {};
        const defaultUser = [];
        if (currentNode.examineRoles && currentNode.examineRoles.length) {
          currentNode.examineRoles.forEach(i => {
            i.aduitors.forEach(j => {
              if (!defaultUser.find(k => k.id === j.id)) {
                defaultUser.push(j.id);
              }
            });
          });
        }
        if (defaultUser.includes(this.userInfo.id)) {
          return true;
        } else {
          return false;
        }
      }
    },
    isApply() { // 申请人
      const proposerId = this.issueInvoiceInfo && this.issueInvoiceInfo.proposerId ? this.issueInvoiceInfo.proposerId : '';
      return proposerId && this.userInfo.id === proposerId;
    },
    // 审批中和已完成，拥有【修改发票权限】可对发票信息进行编辑
    hasInvoiceChangePermission() {
      return hasRouteAuth('crm:invoiceIssue:invoiceChange') && [1, 2].includes(this.issueInvoiceInfo.processStatus);
    },
    // 发票信息是否可编辑
    canEditInvoiceInfo() {
      return this.isCurrentVersion && (this.hasInvoiceChangePermission || this.invoiceInfoIsEdit);
    },
    // 可以关联到账流水
    canAssociate() {
      return this.isCurrentVersion && this.operationSetEvents.includes(EVENT_TYPE.RELEATE_FINANCE_TXN) && this.isCurrentUserApproval;
    },
    // 显示底部保存按钮
    showSaveBtn() {
      return this.issueInvoiceInfo.processStatus !== 3 && (this.canEditInvoiceInfo || this.canAssociate);
    }
  },
  watch: {
    'issueInvoiceInfo.supplierType': {
      handler: function() {
        this.flag = false;
        this.$nextTick(() => {
          this.flag = true;
        });
      },
      deep: true
    },
    'issueInvoiceInfo.orderTotalAmount'(val) {
      if (val || val === 0 || val === 0.00) {
        const numVal = Number(val);
        this.issueInvoiceInfo.orderTotalAmount = isNaN(numVal) ? 0 : numVal.toFixed(2);
      }
    }
  },
  created() {
    this.initData();
  },
  methods: {
    hasRouteAuth,
    initData() {
      this.initRouteData();
      this.queryProcessData(); // 流程数据
    },
    initRouteData() {
      this.issueId = this.$route.query.issueId;
      this.processId = this.$route.query.processId;
      if (!this.issueId || !this.processId) {
        this.$message.warning('无法获取ID');
        const timer = setTimeout(() => {
          this.$router.back();
          clearTimeout(timer);
        }, 1500);
      }
    },
    // 获取基本信息
    queryIssueInvoiceDetail() {
      this.pageLoading = true;
      getIssueInvoiceDetail(this.issueId).then(res => {
        this.handleProcessCheck(res.data.processId);
        this.handleDetailData(res);
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
        this.pageLoading = false;
      });
    },
    // 处理详情接口返回的数据
    handleDetailData(res) {
      this.pageLoading = false;
      if (res.code === 200) {
        if (res.data.processStatus === 3) { // 3为撤销
          this.isRevoke = true;
        } else {
          this.stepActiveId = res.data.processStatus;
          this.isRevoke = false;
        }
        this.issueInvoiceInfo = res.data;
        this.invoiceVersion = res.data.invoiceVersion;
        this.$nextTick(() => {
          this.$refs['contractInfoRef'] && this.$refs['contractInfoRef'].setDefault(res.data.contractInfo || []);
          this.$refs['invoiceInfoRef'] && this.$refs['invoiceInfoRef'].setTableData(res.data.invoiceInfo || []);
        });
      }
    },
    queryProcessData() {
      this.queryIssueInvoiceDetail();
      this.getAuditSchedule();
      this.$nextTick(() => {
        this.$refs.examineAndApproveRef && this.$refs.examineAndApproveRef.getProcessList();
      });
    },
    // 保存开票信息
    saveInvoice() {
      this.$refs['invoiceInfoRef'].validateForm().then(_ => {
        const params = {};
        params.id = this.issueId;
        params.invoiceInfo = this.$refs['invoiceInfoRef'].orders;
        return new Promise((resolve, reject) => {
          storeIssueInvoiceInfo(params).then(res => {
            res.code === 200 && this.$message.success('保存成功');
            resolve(res.code);
          }).catch(e => {
            reject(e);
          });
        });
      }).catch(errMessage => {
        errMessage && this.$message.warning(errMessage);
      });
    },
    // 保存开票信息&到账流水
    async saveNodeEventInfo(type = 1) { // 拒绝时无需校验,0拒绝，1同意, 2保存
      this.saveLoading = true;
      let associateIsOk = false;
      let invoiceIsOk = false;
      // 是否需要保存关联流水
      if (this.canAssociate) {
        if ((!this.issueInvoiceInfo.financeTxnList || this.issueInvoiceInfo.financeTxnList.length === 0) && type !== 0) {
          this.$message.warning('请设置关联到账流水');
          this.saveLoading = false;
          return new Promise((resolve, reject) => {
            reject();
          });
        }
        // taxpayerType  0:公司  1:个人
        // 纳税人为公司时，到账流水的所有付款人必须与纳税人一致
        if (this.issueInvoiceInfo.isArrival && this.$refs['receiptInfoRef'] && this.issueInvoiceInfo.taxpayerType === 0) {
          const financeTxnList = this.issueInvoiceInfo.financeTxnList;
          if (financeTxnList && financeTxnList.length) {
            const isSame = financeTxnList.every(i => i.clientName === this.issueInvoiceInfo.taxpayer && i.clientType === 0);
            if (!isSame) {
              showModal('您提交的审批单中纳税人名称与付款人名称不一致或公司/个人类型不统一，请重新填写。', '', {
                confirmButtonText: '确定',
                showCancelButton: false,
                type: 'warning',
                showClose: false,
                center: true,
                iconClass: 'charge-icon',
                customClass: 'del-message'
              }).then(() => {});
              this.saveLoading = false;
              return;
            }
          }
        }

        let financeTxnIds = '';
        if (this.issueInvoiceInfo.financeTxnList && this.issueInvoiceInfo.financeTxnList.length) {
          financeTxnIds = this.issueInvoiceInfo.financeTxnList.map(item => item.id).join();
        }
        const res = await storeIssueFinance(this.issueId, { financeTxnIds, type });
        this.saveLoading = false;
        if (type === 2 && res.code === 200) associateIsOk = true;
        if (res.code !== 200) {
          return new Promise((resolve, reject) => {
            reject();
          });
        }
      }
      // 是否需要保存开票信息
      if (this.canEditInvoiceInfo) {
        const params = {};
        params.id = this.issueId;
        params.type = type;
        params.invoiceInfo = this.$refs['invoiceInfoRef'].orders;
        params.invoiceVersion = this.invoiceVersion;
        if (type === 0 && !params.invoiceInfo.length) { // 拒绝且发票信息为空时不校验发票内容
          const res = await storeIssueInvoiceInfo(params);
          this.saveLoading = false;
          if (res.code !== 200) {
            return new Promise((resolve, reject) => {
              reject();
            });
          }
        } else {
          await this.$refs.invoiceInfoRef.validateForm().then(async() => {
            // 开启开票填写事件时保存发票信息不能为空
            if (type === 2 &&
              this.operationSetEvents.includes(EVENT_TYPE.INVOICE_APPLY_EDIT_INVOICE) &&
              (!Array.isArray(params.invoiceInfo) || !params.invoiceInfo.length)) {
              this.saveLoading = false;
              this.$message.error('发票信息不能为空!');
            } else {
              const res = await storeIssueInvoiceInfo(params);
              this.saveLoading = false;
              if (type === 2 && res.code === 200) invoiceIsOk = true;
              if (res.code !== 200) {
                return new Promise((resolve, reject) => {
                  reject();
                });
              }
            }
          }).catch(_ => {
            this.saveLoading = false;
            return new Promise((resolve, reject) => {
              reject(false);
            });
          });
        }
      }
      this.saveLoading = false;
      if (
        type === 2 &&
        (!this.canAssociate || (this.canAssociate && associateIsOk)) &&
        (!this.canEditInvoiceInfo || (this.canEditInvoiceInfo && invoiceIsOk))
      ) {
        this.$message.success('保存成功');
      }
      this.queryIssueInvoiceDetail();
    },
    setProcessData(processData) {
      this.processData = processData;
      this.operationSetEvents = this.processData.operation.setEvents || [];
    },
    toBack() {
      if (this.$route.query.fromTodo) {
        this.$router.go(-1);
      } else {
        this.$router.push({ name: 'issueInvoice' });
      }
    },
    getAuditSchedule() {
      this.requestAuditSchedule(this.processId);
    },
    selectFinance(val) {
      this.issueInvoiceInfo.financeTxnList = val;
    },
    handleDeleteReceipt(val) {
      showModal('确定删除该到账流水?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        const index = this.issueInvoiceInfo.financeTxnList.findIndex(cur => { return cur.id === val; });
        this.issueInvoiceInfo.financeTxnList.splice(index, 1);
        // 到账流水列表删除后页数显示
        if (this.issueInvoiceInfo.financeTxnList.length >= 10) {
          const page = this.$refs.receiptInfoRef.page;
          const perPage = this.$refs.receiptInfoRef.perPage;
          const list = this.issueInvoiceInfo.financeTxnList.slice((page - 1) * perPage, page * perPage);
          if (list.length === 0 && page !== 1) {
            this.$refs.receiptInfoRef.page = this.$refs.receiptInfoRef.page - 1;
          }
        }
      }).catch(() => {
        return false;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.issue-invoice-detail-container{
  margin:	16px;
  background: #fff;
  min-height: calc(100vh - 64px);
  .issue-invoice-detail-content{
    position: relative;
    padding: 0 24px 56px;
    .order-info-table {
      ::v-deep .el-table {
        margin-left: 0 !important;
      }
    }
  }
  &::v-deep {
    .explanation-container{
      .explanation{
        padding-left: 32px!important;
      }
    }
  }
  .revoke-img{
    position: absolute;
    width: 80px;
    height: 80px;
    right: 56px;
    top: 33px;
    z-index: 999;
  }
}
::v-deep .el-drawer {
  min-width: 300px;
}
::v-deep .el-form-item__label {
  color: #999;
}
::v-deep .el-form-item {
  margin-bottom: 0 !important;
}
::v-deep .explanation {
  margin-bottom: 0;
}
.issue-invoice-detail-container {
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding-bottom: 55px;
  min-height: calc(100vh - 64px);
}
</style>
